<template>
	<view class="base-page-white yangsf-flex-col">
		<view style="flex: 1; overflow-y: auto; padding-bottom: 100px;">

			<view class="yangsf-ratio-w-100">
				<view class="from-title">
					<image src="/static/icon/sx.png"></image>
					<span class="from-title-text">对方姓名({{prompt}})</span>
				</view>
				<view class="from-item">
					<view class="yangsf-ratio-h-40 yangsf-flex-col-center" @click="toAddUserPage">
						<u--input v-model="contract.userName" inputAlign="center" placeholder="填写正确才能生效" border="bottom"
							readonly suffixIcon="arrow-right"></u--input>
					</view>
				</view>

				<view class="yangsf-ratio-w-100">
					<view class="from-title">
						<image src="/static/icon/sx.png"></image>
						<span class="from-title-text">借款金额</span>
					</view>
					<view class="from-item">
						<view class="yangsf-ratio-h-40">
							<u-number-box integer v-model="contract.money" @change="valChange" :min="0" :step="100"
								button-size="18" inputWidth="100"></u-number-box>
						</view>
					</view>
				</view>

				<view class="yangsf-ratio-w-100">
					<view class="from-title">
						<image src="/static/icon/sx.png"></image>
						<span class="from-title-text">借款利率(年化利率)</span>
					</view>
					<view class="from-item">
						<view class="yangsf-ratio-h-40" @click="showRates = true">
							<u-picker :show="showRates" :columns="rates" keyName="label" @confirm="confirmRates"
								@close="closeRates" @cancel="closeRates"></u-picker>
							<span style="color: #5B86E5; font-size: 36rpx;">{{contract.moneyRate}}%</span>
						</view>
					</view>
				</view>

				<view class="yangsf-ratio-w-100">
					<view class="from-title">
						<image src="/static/icon/sx.png"></image>
						<span class="from-title-text">借款时间</span>
					</view>
					<view class="from-item">
						<view class="yangsf-ratio-h-40 yangsf-flex-col-center">
							<u--input v-model="contract.loanDate" inputAlign="center" border="none" placeholder="借款日期"
								readonly></u--input>
						</view>
					</view>
				</view>







				<view class="yangsf-ratio-w-100">
					<view class="from-title">
						<image src="/static/icon/sx.png"></image>
						<span class="from-title-text">分期设置</span>
					</view>
					<view class="from-item">
						<view class="yangsf-ratio-h-40" @click="showStagesAndDays = true">
							<u-picker :show="showStagesAndDays" :columns="stagesAndDaysColumns" keyName="label"
								@confirm="confirmStagesAndDays" @close="closeStagesAndDays"
								@cancel="closeStagesAndDays"></u-picker>
							<span
								style="color: #5B86E5; font-size: 36rpx;">{{contract.stages}}期，每期{{contract.stageDays}}天</span>
						</view>
					</view>
				</view>

				<view class="yangsf-ratio-w-100" v-if="computedRepaymentDetails.length > 0">
					<view class="from-title">
						<image src="/static/icon/sx.png"></image>
						<span class="from-title-text">还款详情</span>
					</view>
					<table class="repayment-table">
						<thead>
							<tr>
								<th>期数</th>
								<th>还款日期</th>
								<th>还款金额</th>
								<th>本金</th>
								<th>利息</th>
							</tr>
						</thead>
						<tbody>
							<tr v-for="(item, index) in computedRepaymentDetails" :key="index">
								<td>{{ item.level }}</td>
								<td>{{ item.expireDate }}</td>
								<td>{{ item.money }}</td>
								<td>{{ item.principal }}</td>
								<td>{{ item.interest }}</td>
							</tr>
						</tbody>
					</table>
				</view>

				<view class="yangsf-ratio-w-100">
					<view class="from-title">
						<image src="/static/icon/sx.png"></image>
						<span class="from-title-text">借款用途</span>
					</view>
					<view class="from-item">
						<view class="yangsf-ratio-h-40" @click="showPurpose = true">
							<u-picker :show="showPurpose" :columns="purposes" keyName="label" @confirm="confirmPurpose"
								@close="closePurpose" @cancel="closePurpose"></u-picker>
							<span :style="!purpose?'color:#c1c1c1':''">{{!purpose?'请选择':purpose}}</span>
						</view>
					</view>
				</view>

			</view>
		</view>

		<view v-if="!(contract.id && contract.signNo.id > 0)" class="yangsf-page-bottom-button yangsf-card">
			<view class="yangsf-flex-row-center">
				<view class="yangsf-ratio-w-80 ">
					<u-button type="primary" text="发起合同" @click="check"></u-button>
				</view>
			</view>
		</view>


		<u-modal :show="showPayPassword" title="支付密码" @confirm="confirm" :closeOnClickOverlay="true">
			<view class="">
				<u-code-input v-model="payPassword" :maxlength="6" dot></u-code-input>
			</view>
		</u-modal>
	</view>
</template>

<script>
	import {
		saveContract,
		checkPayPassword
	} from '@/config/api.js'
	import {
		purposes
	} from '@/config/config.js'
	export default {
		data() {
			return {
				purposes: purposes,
				isCheckPay: false,
				showPayPassword: false,
				payPassword: '',
				prompt: '',
				showRates: false,

				showLoanDate: false,
				showPurpose: false,
				showStagesAndDays: false,
				purpose: '',
				stagesAndDaysColumns: [
					Array.from({
						length: 24
					}, (v, k) => ({
						label: `${k + 1}期`,
						value: k + 1
					})),
					Array.from({
						length: 30
					}, (v, k) => ({
						label: `${k + 1}天`,
						value: k + 1
					}))
				],
				minLoanDate: Date.now(), // 最小日期为当前日期
				maxLoanDate: Date.now() + 90 * 24 * 60 * 60 * 1000, // 最大日期为当前日期后3个月
				contract: {
					isTag: 1, // 1是分期，0否
					kind: '',
					userName: '',
					userCardNo: '',
					userTele: '',
					money: 1000,
					moneyRate: 0,
					loanDate: uni.$u.timeFormat(Date.now(), 'yyyy-mm-dd'),
					stages: 1, // 分期期数
					stageDays: 1
				},
				rates: [
					[{
						label: '0%',
						value: 0
					}, {
						label: '1%',
						value: 1
					}, {
						label: '2%',
						value: 2
					}, {
						label: '3%',
						value: 3
					}, {
						label: '4%',
						value: 4
					}, {
						label: '5%',
						value: 5
					}, {
						label: '6%',
						value: 6
					}, {
						label: '7%',
						value: 7
					}, {
						label: '8%',
						value: 8
					}, {
						label: '9%',
						value: 9
					}, {
						label: '10%',
						value: 10
					}, {
						label: '11%',
						value: 11
					}, {
						label: '12%',
						value: 12
					}, {
						label: '13%',
						value: 13
					}, {
						label: '14%',
						value: 14
					}]
				],
			}
		},
		onLoad(opthon) {
			console.log("opthon ==> {}", opthon);
			//1.出借人 0.借款人
			this.contract.kind = opthon.kind
			if (this.contract.kind == 1) {
				this.prompt = '借款方';
			} else {
				this.prompt = '出借方';
			}
		},
		methods: {
			check() {
				if (!this.contract.userName || !this.contract.userCardNo) {
					uni.$u.toast("请填写对方信息")
					return
				}
				if (!this.contract.money) {
					uni.$u.toast("请填写借款金额")
					return
				} else {
					if (this.contract.money <= 0) {
						uni.$u.toast("借款金额不能为0元")
						return
					}
				}
				// if (!this.contract.moneyRate) {
				// 	uni.$u.toast("请填写借款利率")
				// 	return
				// }
				if (!this.contract.loanDate) {
					uni.$u.toast("请选择借款日期")
					return
				}

				if (!this.contract.purpose) {
					uni.$u.toast("请选择借款用途")
					return
				}

				if (!this.isCheckPay) {
					this.showPayPassword = true
				} else {
					let remark =
						`总还款金额:${this.computedTotalMoney}元，分${this.contract.stages}期，每期${this.contract.stageDays}天。`;
					this.contract.remark = remark;
					this.save();
				}

			},
			confirm() {
				let data = {
					payPassword: this.payPassword
				}
				checkPayPassword(data).then(res => {
					if (res.code == 200) {
						this.isCheckPay = true
						this.showPayPassword = false
						this.check();
					}
				})
			},
			valChange(e) {
				// console.log('当前值为: ' + e);
				this.contract.money = e;
			},
			selectLoanDate() {
				// 更新日期限制，确保每次打开选择器时都使用最新的当前日期
				this.minLoanDate = Date.now();
				this.maxLoanDate = Date.now() + 90 * 24 * 60 * 60 * 1000; // 3个月 = 90天
				this.showLoanDate = true;
			},
			confirmLoanDate(e) {
				// console.log("选择借款日期 ==> {}, {}", e.value, e.mode);
				this.contract.loanDate = uni.$u.date(e.value, 'yyyy-mm-dd')
				this.cancelLoanDate()
				// this.compute()
			},
			cancelLoanDate() {
				this.showLoanDate = false
			},

			toAddUserPage() {
				uni.$u.route('/pages/contract/addUser', {
					userName: this.contract.userName,
					userCardNo: this.contract.userCardNo,
					userTele: this.contract.userTele
				});
			},
			setUserMsg(data) {
				console.log('收到子页面传来的数据:', data);
				this.contract.userName = data.userName
				this.contract.userCardNo = data.userCardNo
				this.contract.userTele = data.userTele
			},
			confirmRates(e) {
				// console.log("利率 ==> {}", e);
				this.contract.moneyRate = e.value[0].value
				this.closeRates()
			},
			closeRates() {
				this.showRates = false
			},
			confirmPurpose(e) {
				this.purpose = e.value[0].label
				this.contract.purpose = e.value[0].value
				this.closePurpose()
			},
			closePurpose() {
				this.showPurpose = false
			},
			confirmStagesAndDays(e) {
				// console.log("confirmStagesAndDays: 确认分期和天数");
				// console.log("confirmStagesAndDays: 选择的期数=", e.value[0].value, "选择的天数=", e.value[1].value);
				this.contract.stages = e.value[0].value; // 确保 stages 和 stagesNum 保持一致
				this.contract.stageDays = e.value[1].value;
				// console.log("confirmStagesAndDays: 调用 computeFenQi 之前 totalMoney=", this.contract.totalMoney);
				this.closeStagesAndDays();
				// this.computeFenQi(); // 移除手动调用
				// console.log("confirmStagesAndDays: 调用 computeFenQi 之后 totalMoney=", this.contract.totalMoney);
			},
			closeStagesAndDays() {
				this.showStagesAndDays = false;
			},
			save() {
				// 在发送前将计算属性的值赋给 contract.totalMoney
				this.contract.totalMoney = this.computedTotalMoney;
				// 将分期详情添加到合同对象中
				this.contract.stageList = this.computedRepaymentDetails;
				this.contract.repayment = this.contract.stageList[0].expireDate
				saveContract(this.contract).then(res => {
					if (res.code == 200) {
						// uni.$u.toast("发起成功")
						uni.$u.route('/pages/contract/share', {
							id: res.data.signNo
						});
					} else {
						uni.$u.toast(res.msg)
					}
				})
			}

		},
		computed: {
			computedRepaymentDetails() {
				// console.log("computedRepaymentDetails: 开始计算");
				const {
					money,
					moneyRate,
					stages,
					stageDays,
					loanDate
				} = this.contract;
				let details = [];

				// console.log(`computedRepaymentDetails: money=${money}, moneyRate=${moneyRate}, stages=${stages}, stageDays=${stageDays}, loanDate=${loanDate}`);
				if (!money || !stages || !stageDays || !loanDate) {
					// console.log("computedRepaymentDetails: 缺少必要参数，返回空数组");
					return [];
				}

				const principalPerStage = money / stages; // 每期应还本金
				let remainingPrincipal = money;

				for (let i = 0; i < stages; i++) {
					const currentInterest = remainingPrincipal * (moneyRate / 100) * (stageDays / 365); // 每期利息
					const currentRepayment = principalPerStage + currentInterest; // 每期总还款

					// 计算还款日期
					const startDate = new Date(loanDate);
					const repaymentDate = new Date(startDate.getTime() + (i + 1) * stageDays * 24 * 60 * 60 * 1000);
					const formattedRepaymentDate = uni.$u.date(repaymentDate, 'yyyy-mm-dd');

					details.push({
						level: i + 1,
						principal: principalPerStage.toFixed(2),
						interest: currentInterest.toFixed(2),
						money: currentRepayment.toFixed(2),
						expireDate: formattedRepaymentDate
					});

					remainingPrincipal -= principalPerStage;
				}
				// console.log("computedRepaymentDetails: 计算完成。", details);
				return details;
			},
			computedTotalMoney() {
				// console.log("computedTotalMoney: 开始计算");
				const {
					money
				} = this.contract;
				let totalInterest = 0;
				this.computedRepaymentDetails.forEach(item => {
					totalInterest += parseFloat(item.interest);
				});
				const total = (money + totalInterest).toFixed(2);
				// console.log("computedTotalMoney: 计算完成。total=", total);
				return total;
			}
		}
	}
</script>

<style scoped>
	.from-title {
		height: 20px;
		margin-left: 20px;
		margin-top: 20px;

		display: flex;
		align-items: center;
	}

	.from-title>image {
		width: 5%;
		height: 100%;
	}

	.from-title-text {
		color: #54545C;
		font-size: 30rpx;
		font-weight: bold;
	}

	.from-item {
		margin-top: 20rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.card_lx {
		margin-top: 30px;
		height: 40px;
		background-color: #fff;

		border-radius: 8px;
		border: 1px solid #c1c1c1;
	}

	.repayment-table {
		width: 90%;
		margin: 20px auto;
		border-collapse: collapse;
		text-align: center;
	}

	.repayment-table th,
	.repayment-table td {
		border: 1px solid #e4e4e4;
		padding: 8px;
		font-size: 12px;
		/* 减小字体大小 */
		white-space: nowrap;
		/* 防止文本换行 */
	}

	.repayment-table th {
		background-color: #f5f5f5;
		font-weight: bold;
	}

	.repayment-table tr:nth-child(even) {
		background-color: #f9f9f9;
	}

	.repayment-table tr:hover {
		background-color: #f1f1f1;
	}
</style>